import {
  ArgumentsHost,
  BadRequestException,
  Catch,
  ExceptionFilter,
  HttpStatus,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';
import { ResponseCodeEnum } from '../enums/response-code.enum';
import { BusinessException } from '../exceptions/business.exception';
import { Prisma } from '@prisma/client';

@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    console.log('AllExceptionFilter', exception);
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();

    // 原有的其他异常处理逻辑...
    const status = this.getStatus(exception);
    const message = this.getMessage(exception);
    const data = null;

    let code = status;
    if (exception instanceof Prisma.PrismaClientKnownRequestError) {
      code = ResponseCodeEnum.DATABASE_ERROR;
    } else if (exception instanceof BusinessException) {
      code = exception.getErrorCode();
    }

    response.status(status).json({
      code,
      message,
      data,
    });
  }

  getStatus(exception: unknown): number {
    if (exception instanceof BadRequestException) {
      return HttpStatus.BAD_REQUEST;
    } else if (exception instanceof HttpException) {
      return exception.getStatus();
    } else {
      return HttpStatus.INTERNAL_SERVER_ERROR;
    }
  }

  getMessage(exception: unknown): string {
    if (exception instanceof Prisma.PrismaClientKnownRequestError) {
      return '数据库操作异常';
    } else if (exception instanceof BusinessException) {
      return exception.message;
    } else if (exception instanceof BadRequestException) {
      return exception.message;
    } else if (exception instanceof HttpException) {
      return exception.message;
    } else {
      return '系统异常';
    }
  }
}
